package com.btpj.shop.controller;

import com.btpj.shop.dto.BannerDto;
import com.btpj.shop.dto.CommonResult;
import com.btpj.shop.dto.param.BannerParam;
import com.btpj.shop.service.BannerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Api(tags = "轮播图接口")
@RestController
@RequestMapping("/banner")
public class BannerController {

    @Resource
    private BannerService bannerService;

    @ApiOperation("添加轮播图")
    @PostMapping("/admin/add")
    public CommonResult<Void> addBanner(@RequestBody @Validated BannerParam bannerParam) {
        if (bannerService.addBanner(bannerParam)) {
            return CommonResult.success("添加轮播图成功");
        }
        return CommonResult.error("服务器出错，添加轮播图失败");
    }

    @ApiOperation("修改轮播图")
    @ApiImplicitParam(name = "id", value = "轮播图ID", required = true, dataType = "Long", paramType = "path")
    @PutMapping("/admin/update/{id}")
    public CommonResult<Void> updateBanner(@PathVariable Long id, @RequestBody @Validated BannerParam bannerParam) {
        if (!bannerService.exists(id)) {
            return CommonResult.error("指定ID为" + id + "的轮播图不存在");
        }
        if (bannerService.updateBanner(id, bannerParam)) {
            return CommonResult.success("修改轮播图成功");
        }
        return CommonResult.error("服务器出错，修改轮播图失败");
    }

    @ApiOperation("批量删除轮播图（多个以,隔开即可）")
    @ApiImplicitParam(name = "ids", value = "轮播图ID集", required = true, dataType = "Long", paramType = "path", allowMultiple = true)
    @DeleteMapping("/admin/delete/{ids}")
    public CommonResult<Void> deleteBanners(@PathVariable Long[] ids) {
        for (Long id : ids) {
            if (!bannerService.exists(id)) {
                return CommonResult.error("指定ID为" + id + "的轮播图不存在");
            }
        }

        if (bannerService.deleteBanners(ids)) {
            return CommonResult.success("删除轮播图成功");
        }
        return CommonResult.error("服务器出错，删除轮播图失败");
    }

    @ApiOperation("获取轮播图列表")
    @GetMapping("/list")
    public CommonResult<List<BannerDto>> getBannerDtoList() {
        return CommonResult.success(bannerService.getBannerDtoList());
    }
}
